package zhcms.tool;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import zhcms.framework.Action;
import zhcms.framework.ActionForward;


public class RandImgCreater implements Action {
	
	public ActionForward creatimage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("image/jpeg"); 
    	// 产生四位随机验证码  
    	StringBuffer sb = new StringBuffer(4);
    	for (int i = 0; i < 4; i++) {
    		int n = (int) (Math.random() * 10);
    		sb.append(n);  
    	}
    	String validateCode = sb.toString();
    	request.getSession().setAttribute("checkcode", validateCode);
    	// 创建缓存图片
    	BufferedImage image = new BufferedImage(50, 25,BufferedImage.TYPE_INT_RGB);
    	Graphics g = image.getGraphics();
    	 
    	g.setColor(Color.LIGHT_GRAY);
    	g.fillRect(0, 0, 80, 25);
    	g.setColor(Color.BLACK);
    	 
    	g.drawString(validateCode, 10, 18);
    	g.dispose();
  
    	ServletOutputStream outStream = response.getOutputStream();
    	//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
    	//encoder.encode(image);
    	try {
            ImageIO.write(image, "JPEG", outStream);//将内存中的图片通过流动形式输出到客户端
        } catch (Exception e) {
            e.printStackTrace();
        	}
    	outStream.close();
    	
    	
    	
    	return new ActionForward("/index.jsp",3);
    }
    
	@Override
	public ActionForward excute(HttpServletRequest request,
			HttpServletResponse response) {
		return null;
	}

}
